//
//  USTodayTarotController.m
//  us
//
//  Created by karry on 2025/5/13.
//

#import "USTodayTarotController.h"
#import "USAlertTipBar.h"
#import "USTarotCardView.h"
#import "USTarotCardPreview.h"
#import "USTarotCardDetailController.h"
#import "USTarotAskLoadingView.h"
#import "AIManager.h"

@interface USTodayTarotController ()

@property (nonatomic,strong) UIView *boxView;
@property (nonatomic,strong) UIView *containerView;
@property (nonatomic,strong) USAlertTipBar *tipBar;
@property (nonatomic,strong) UIView *circleContainer;
@property (nonatomic, assign) CGFloat currentRotation; // 当前总旋转角度
@property (nonatomic,strong) UIButton *actionBtn;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) USTarotCardPreview *cardPreview;

@property (nonatomic, assign) SystemSoundID soundID;

@property (nonatomic) CGAffineTransform fromTransform;
@property (nonatomic) CGPoint fromPoint0;
@property (nonatomic) CGPoint fromPoint;
@property (nonatomic) CGPoint sourceCardfromPoint;
@property (nonatomic) CGRect fromBounds;
@property (nonatomic) USTarotCardView *seletedCardView;


@end

@implementation USTodayTarotController

- (USTarotCardPreview *)cardPreview{
    if (!_cardPreview) {
        _cardPreview = [[USTarotCardPreview alloc]initWithFrame:self.view.window.bounds];
        @weakify(self)
        _cardPreview.closeBlock = ^{
            @strongify(self)
            [self cancelPreview];
        };
        _cardPreview.didSeletedCardBlock = ^(USTarotCard * _Nonnull card) {
            @strongify(self)
//            USTarotCardDetailController *vc = [USTarotCardDetailController new];
//            vc.activeCard = card;
            
            [self gotoLoadCard:card navc:self.navigationController];
            [self.navigationController popToRootViewControllerAnimated:NO];
 
            
        };
    }
    return _cardPreview;
}


- (void)gotoLoadCard:(USTarotCard *)card navc:(UINavigationController *)navc{
    
    USTarotAskLoadingView *loadView = [USTarotAskLoadingView show];
    loadView.card = card;
    
    NSString * orientation = card.orientation == USTarotCardOrientationReversed?@"逆位":@"正位";
    @weakify(loadView)
    [AIManager generateTarotReadingWithCardName:card.name orientation:orientation date:[NSDateFormatter localizedStringFromDate:NSDate.date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle] completion:^(NSString * _Nonnull result, NSError * _Nonnull error) {
        
        if (loadView_weak_.window == nil) {
            return;
        }
        [loadView_weak_ dissmiss];
        
        if (error) {
            
            [UIWindow.keyWindow makeToast:error.localizedDescription];
            
        }else{
 
            [USFeedbackTool notifySuccess];
            card.answer = result;
            USTarotCardDetailController *vc = [USTarotCardDetailController new];
            vc.activeCard = card;
            vc.tarotModel = self.tarotModel;
            
            for (USTarotDetailModel *detailModel in self.tarotModel.tarotDetailList) {
                USTarotCard *card = [USTarotCard new];
                
                card = [[USTarotCard alloc] init];
                card.name = detailModel.tarotTitle;
                card.orientation = detailModel.orientation;
                card.imageName = detailModel.tarotTitle;
                card.answer = detailModel.tarotContent;
                card.date = [NSDate dateWithTimeIntervalSince1970:detailModel.gmtCreate];
                if ([detailModel.userId isEqualToString:USUser.user.relUser.userId]) {
                    //对方回答的
                    vc.relActiveCard = card;
                }
            }
            
            [navc popToRootViewControllerAnimated:NO];
            [navc pushViewController:vc animated:YES];

            [self uploadTarotWithCard:card];
        }
        
    }];
    
}

- (void)uploadTarotWithCard:(USTarotCard *)card{
 
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.tarotModel.tarotId?:@"" forKey:@"tarotId"];
    [params setObject:card.name forKey:@"tarotTitle"];
    [params setObject:card.overview forKey:@"tarotSub"];
    [params setObject:card.name forKey:@"tarotUrl"];
    [params setObject:@(card.orientation) forKey:@"orientation"];
    [params setObject:card.answer forKey:@"tarotContent"];

    [[EMNetWork shareManager] em_post:TarotAdd
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        USTarotModel *tarot = [USTarotModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];

        [self remindActionTarot:tarot];
    } fail:^{
 
    }];
}


#pragma mark - 提醒Ta
- (void)remindActionTarot:(USTarotModel *)tarot {
 
    //这里塔罗牌的通知，区分提醒去抽取，和我完成了抽取的提醒（action_id可以考虑用传个不传来区分，提醒抽取可以不传，因为固定是取抽取页面）
    NSString *action_title = [NSString stringWithFormat:@"%@抽取了今天的塔罗牌",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":tarot.tarotId?:@"",
                          @"action_title":action_title,
                          @"action_content":@"点击查看"};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_TarotNotic andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_TarotNotic andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Tarot) forKey:@"type"];
    [param setValue:tarot.tarotId?:@"" forKey:@"pkId"];
    [param setValue:@"抽取了今天的塔罗牌" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}

// 开始接收摇动事件
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        [self ShuffleTheCards];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"今日塔罗牌";
    [self setupView];
    
    // 1️⃣ 加载音效文件
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"c764de9af9d3c2495b88d35d8847bd4a" ofType:@"wav"];
    if (soundPath) {
        NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &_soundID);
    }
    
}

// 2️⃣ 播放音效
- (void)playClickSound {
    AudioServicesPlaySystemSound(1104);
}

- (void)setupView{
    
    USAlertTipBar *tipBar = [[USAlertTipBar alloc]initWithFrame:CGRectZero];
    _tipBar = tipBar;
    tipBar.style = USAlertTipBarStyleDefault;
    tipBar.color = UIColor.us_greenColor;
    tipBar.titleLab.text = @"你的能量正在注入牌组…准备好了吗？";
    tipBar.titleLab.font = [UIFont systemFontOfSize:15];
    
    [self.view addSubview:tipBar];
    [tipBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];

    self.boxView = [[UIView alloc]initWithFrame:CGRectMake(20, 20, self.view.jk_width - 20 * 2, self.view.jk_height - self.view.safeAreaInsets.bottom - [UIButton us_buttonDefaultHeight] - 20 - 20 - 40 - 20)];
    [self.view addSubview:self.boxView];

    [self setupStardCards];
    
    UIButton *actionBtn = [UIButton us_fillButtonWithTitle:@"洗牌"];
    [actionBtn setTitle:@"结束洗牌" forState:UIControlStateSelected];
    _actionBtn = actionBtn;
    [actionBtn addTarget:self action:@selector(reloadCard:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:actionBtn];
    [actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo([UIButton us_buttonDefaultHeight]);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-12);
    }];
    
    [self.boxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.top.mas_equalTo(tipBar.mas_bottom).mas_offset(20);
        make.bottom.mas_equalTo(actionBtn.mas_top).mas_offset(-20);
    }];
    
}

- (void)goNext:(id)sender{
    
    [self resetCards];
    
}

- (void)reloadCard:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        
        [USFeedbackTool impactSoft];
        [self ShuffleTheCards];
        sender.userInteractionEnabled = NO;
        
        @weakify(self)
       self.timer = [NSTimer scheduledTimerWithTimeInterval:0.8 repeats:YES block:^(NSTimer * _Nonnull timer) {
            @strongify(self)
           sender.userInteractionEnabled = YES;
            [self ShuffleTheCards];

        }];
        
        self.tipBar.color = UIColor.us_redColor;
        self.tipBar.titleLab.text = @"思考问题，放空杂念";
        
        
    }else{
        
        [self.timer invalidate];
        self.timer = nil;
        [self resetCards];
        
    }
    
}


- (void)setupStardCards {
    [USFeedbackTool impactSoft];
    
    UIView *containerView = [UIView new];
    _containerView = containerView;
    
    CGFloat h = 0;
    
    CGFloat itemW = 70;
    CGFloat itemH = 120;
    
    for (NSInteger i = 0; i < 78; i++) {
        
        USTarotCardView *card = [[USTarotCardView alloc] initWithFrame:CGRectMake(0, i * 3, itemW, itemH)];
        [containerView insertSubview:card atIndex:0]; // ✅ 添加到容器上

        if (i <= 19) {
            h = CGRectGetMaxY(card.frame); // ✅ 保险地获取最大 y
        }else{
            card.frame = CGRectMake(0, 0, itemW, itemH);
        }
        
    }
    
    CGFloat left = (self.view.frame.size.width - itemW) * 0.5;
    CGFloat top = (self.view.frame.size.height - h) * 0.5;
    
    containerView.frame = CGRectMake(left, top, itemW, h); // ✅ 容器尺寸
    [self.view addSubview:containerView];
    
    // 初始放在左上角
    CGPoint startPoint = CGPointMake(-itemW, -itemH);
    CGPoint endPoint = containerView.center; // 动画目标是 containerView 原始位置（中心点）

    containerView.center = startPoint;

    // 创建贝塞尔曲线路径：从左上 → 屏幕中心，带一个弧度
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];

    // 控制点可以调节曲率（越靠近屏幕右上角越弯）
    CGPoint controlPoint = CGPointMake(startPoint.x - 100, endPoint.y);
    [path addQuadCurveToPoint:endPoint controlPoint:controlPoint];

    // 路径动画
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
    animation.duration = 0.5;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    // 最终位置保持
    containerView.center = endPoint;
    [containerView.layer addAnimation:animation forKey:@"flyIn"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self ShuffleTheCards];
    });
    
}


- (void)resetCards{
    
    [USFeedbackTool impactSoft];
    
    CGFloat itemW = 70;
    CGFloat itemH = 120;
    
    [self.boxView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

        [obj removeFromSuperview];
        obj.frame = [obj.superview convertRect:obj.frame toView:self.containerView];
        [self.containerView insertSubview:obj atIndex:0]; // ✅ 添加到容器上
        
        [UIView animateWithDuration:0.3 animations:^{
            obj.transform = CGAffineTransformIdentity;
            CGRect frame = CGRectMake(0, idx * 3, itemW, itemH);
            if (idx <= 19) {
                obj.frame = frame;
            }else{
                obj.frame = CGRectMake(0, 0, itemW, itemH);
            }
        }];
        
    }];
    
    
    [UIView animateWithDuration:0.3 delay:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
       
        self.containerView.transform = CGAffineTransformMakeTranslation( self.view.jk_width * 0.5 + itemH, 0);
        self.actionBtn.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [self.containerView removeFromSuperview];
        [self.boxView removeFromSuperview];
        [self.actionBtn removeFromSuperview];
        [self setupChooseCards];
        
    }];

}

- (void)setupChooseCards{
    
    self.tipBar.color = UIColor.us_orangeColor;
    self.tipBar.titleLab.text = @"滑动浏览所有卡牌";
    self.tipBar.subLab.text = @"点击选牌";
    [self layoutCardsInFullCircle];
    
}

- (void)layoutCardsInFullCircle {

    NSInteger count = 60; // 总卡牌数
    
    CGFloat radius = (self.view.frame.size.height - self.tipBar.jk_bottom - 20 - self.view.safeAreaInsets.bottom - 90 * 2)*0.5;
    CGSize cardSize = CGSizeMake(90, 90 * 120/70.f);
    
    // 创建一个容器 view 用于包裹所有卡片，方便后续整体旋转
    UIView *circleContainer = [[UIView alloc] initWithFrame:CGRectMake(self.view.jk_width * 0.2, self.tipBar.jk_bottom + 20, radius * 2 + cardSize.height, radius * 2 + cardSize.height)];
    [self.view insertSubview:circleContainer atIndex:0];
    
    // 角度步长 = 360° / 卡数（单位是弧度）
    CGFloat angleStep = 2 * M_PI / count;
    CGPoint circleCenter = CGPointMake(circleContainer.bounds.size.width * 0.5,
                                       circleContainer.bounds.size.height * 0.5);

    for (NSInteger i = 0; i < count; i++) {
        CGFloat angle = i * angleStep;
        // 每张卡片的位置（以圆心为参考点）
        CGFloat x = circleCenter.x + radius * cos(angle);
        CGFloat y = circleCenter.y + radius * sin(angle);
        
        USTarotCardView *card = [[USTarotCardView alloc] initWithFrame:CGRectMake(0, 0, cardSize.width, cardSize.height)];
        [card jk_shadowWithColor:UIColor.whiteColor offset:CGSizeMake(1, 1) opacity:0.3 radius:3];
        card.center = CGPointMake(x, y);
        
        // 旋转卡片面朝外（+ M_PI_2 是朝向圆外）
        card.transform = CGAffineTransformMakeRotation(angle + M_PI_2);
        
        [circleContainer addSubview:card];
    }
    
    // 存起来以便后续旋转
    self.circleContainer = circleContainer;
    [self addRotationGesture];
    
    self.circleContainer.transform = CGAffineTransformMakeTranslation(circleContainer.frame.size.width, 0);
    [UIView animateWithDuration:.5 animations:^{
        self.circleContainer.transform = CGAffineTransformIdentity;
    }];
    
}

- (void)addRotationGesture {
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.circleContainer addGestureRecognizer:pan];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.circleContainer addGestureRecognizer:tap];
    
}

- (void)tapAction:(UITapGestureRecognizer *)sender {
    [USFeedbackTool notifySuccess];
    for (USTarotCardView *card in [self.circleContainer.subviews reverseObjectEnumerator]) {
        // 转换 tap 点到 card 局部坐标
        CGPoint pointInCard = [sender locationInView:card];
        if ([card pointInside:pointInCard withEvent:nil]) {
            [USFeedbackTool notifySuccess];
            [self playClickSound];
            [self handleCardTap:card];
            break;
        }
    }
}


- (void)handleCardTap:(USTarotCardView *)card {
    // 1️⃣ 获取当前卡牌在屏幕中的 frame
    [self presentCardInFullscreenFrom:card];
}

// 展示卡牌全屏动画，包含“拉出”动画步骤
- (void)presentCardInFullscreenFrom:(USTarotCardView *)sourceCard {

    self.seletedCardView = sourceCard;
    
    UIWindow *window = self.view.window;
    self.cardPreview.contentView.alpha = 0;
    self.cardPreview.imageView.layer.cornerRadius = 6;
    [window addSubview:self.cardPreview];
    [self.cardPreview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    UIImageView *toImageView = self.cardPreview.imageView;
    toImageView.alpha = 0;
    toImageView.image = sourceCard.imageView.image;
    toImageView.transform = CGAffineTransformConcat(sourceCard.transform, self.circleContainer.transform);
    toImageView.bounds = sourceCard.bounds;
    toImageView.center = [sourceCard.superview convertPoint:sourceCard.center toView:window];

    // 先做一个“拉出”动画：沿圆心到卡片中心的径向移动
    CGPoint originalCenter = toImageView.center;
    // Compute direction vector from circle center to card center
    CGPoint circleCenter = [self.circleContainer.superview convertPoint:self.circleContainer.center toView:window];
    CGFloat dx = toImageView.center.x - circleCenter.x;
    CGFloat dy = toImageView.center.y - circleCenter.y;
    CGFloat length = sqrt(dx*dx + dy*dy);
    if (length == 0) length = 1; // avoid divide by zero
    CGFloat offset = 50.f;
    CGPoint pullOutOffset = CGPointMake((dx / length) * offset, (dy / length) * offset);

    CGPoint center = CGPointMake(originalCenter.x + pullOutOffset.x,
                                 originalCenter.y + pullOutOffset.y);

    CGPoint s_center = [window convertPoint:center toView:self.circleContainer];
    
    self.fromPoint0 = toImageView.center;
    self.sourceCardfromPoint = sourceCard.center;
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
            toImageView.center = center;
            sourceCard.center = s_center;
            sourceCard.alpha = 0;
            toImageView.alpha = 1;
        
        
    } completion:^(BOOL finished) {
        
        [USFeedbackTool impactSoft];
        
        self.fromPoint = toImageView.center;
        self.fromTransform = toImageView.transform;
        self.fromBounds = toImageView.bounds;
        // ✅ 正确版本
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                
            toImageView.center = window.center;
            toImageView.transform = CGAffineTransformIdentity;;
            CGFloat w = window.frame.size.width;
            w = w - 50 * 2;
            CGFloat h = w * 12/7.f;
            toImageView.bounds = CGRectMake(0, 0, w, h);
            self.cardPreview.contentView.alpha = 1;
            toImageView.layer.cornerRadius = 20;
            
        } completion:nil];
        
    }];
    

    
}

- (void)cancelPreview{
    
    UIImageView *toImageView = self.cardPreview.imageView;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        toImageView.center = self.fromPoint;
        toImageView.transform = self.fromTransform;
        toImageView.bounds = self.fromBounds;
        toImageView.layer.cornerRadius = 1;
        self.cardPreview.contentView.alpha = 0;
    
    }completion:^(BOOL finished) {
     
        [USFeedbackTool impactSoft];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            toImageView.center = self.fromPoint0;
            self.seletedCardView.center = self.sourceCardfromPoint;
            self.seletedCardView.alpha = 1;
            toImageView.alpha = 0;
            
        }completion:^(BOOL finished) {
            
            [self.cardPreview removeFromSuperview];
            self.cardPreview = nil;
            
        }];
        
    }];
    
}


- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    static CGFloat lastAngle = 0;
    static CGFloat lastFeedbackAngle = 0;
    static UIImpactFeedbackGenerator *feedbackGen;

    if (!feedbackGen) {
        feedbackGen = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [feedbackGen prepare];
    }

    UIView *circle = gesture.view;
    CGPoint location = [gesture locationInView:circle.superview];
    CGPoint center = circle.center;

    CGFloat dx = location.x - center.x;
    CGFloat dy = location.y - center.y;
    CGFloat angle = atan2(dy, dx);

    if (gesture.state == UIGestureRecognizerStateBegan) {
        lastAngle = angle;
        lastFeedbackAngle = 0;
    } else if (gesture.state == UIGestureRecognizerStateChanged) {
        CGFloat delta = angle - lastAngle;
        lastAngle = angle;

        circle.transform = CGAffineTransformRotate(circle.transform, delta);

        // 记录并累加旋转角度
        lastFeedbackAngle += delta;

        // 当旋转超过 10°，触发一次反馈
        CGFloat feedbackThreshold = M_PI / 18.0; // 约 10°
        if (fabs(lastFeedbackAngle) >= feedbackThreshold) {
            [USFeedbackTool selectionChanged];
            [self playClickSound];
            lastFeedbackAngle = 0; // 重置
        }
        
        __block NSInteger startIndex = 0;
        
        [circle.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect cardFrameInScreen = [obj.superview convertRect:obj.frame toView:nil];
            CGRect screenBounds = UIScreen.mainScreen.bounds;

            if (!CGRectIntersectsRect(cardFrameInScreen, screenBounds)) {
                // 卡片已经完全在屏幕外
                startIndex = idx;
                *stop = YES;
                return;
            }
            
        }];
        
        NSArray<UIView *> *cards = circle.subviews;

        for (NSInteger i = startIndex; i < cards.count; i++) {
            [circle bringSubviewToFront:cards[i]];
        }

        for (NSInteger i = 0; i < startIndex; i++) {
            [circle bringSubviewToFront:cards[i]];
        }
    }
    
}


- (void)ShuffleTheCards {
    
    NSArray<USTarotCardView *> *cards = self.containerView.subviews;
    if (cards.count == 0) {
        cards = self.boxView.subviews;
    }else{
        
        [cards enumerateObjectsUsingBlock:^(USTarotCardView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.center = self.boxView.center;
            [obj removeFromSuperview];
            [self.boxView addSubview:obj];
        }];
    }

    CGFloat itemW = 70;
    CGFloat itemH = 120;
    
    CGFloat boxW = self.boxView.frame.size.width;
    CGFloat boxH = self.boxView.frame.size.height;

    // 限定范围，确保卡片中心点在 boxView 可见区域内
    CGFloat minX = itemW * 0.5;
    CGFloat maxX = boxW - itemW * 0.5;
    CGFloat minY = itemH * 0.5;
    CGFloat maxY = boxH - itemH * 0.5;
    
    for (NSInteger i = 0; i < cards.count; i++) {
        USTarotCardView *card = cards[i];

        // 设置随机角度 [-10°, +10°]
        CGFloat angle = ((float)arc4random() / UINT32_MAX) * 2 * M_PI;

        // 放置到中心堆叠
        card.transform = CGAffineTransformIdentity;
        card.transform = CGAffineTransformMakeRotation(angle);

        CGFloat randX = ((float)arc4random() / UINT32_MAX) * (maxX - minX) + minX;
        CGFloat randY = ((float)arc4random() / UINT32_MAX) * (maxY - minY) + minY;

        CGPoint endPoint = CGPointMake(randX, randY);

        [UIView animateWithDuration:0.3 delay:0.f options:UIViewAnimationOptionCurveEaseOut animations:^{
            card.center = endPoint;
        } completion:nil];

    }
    
}

@end
